package cn.cloudtogo.common.util;

import cn.cloudtogo.common.types.ConnectString;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;

/**
 * @author yaolianhua789@gmail.com
 **/
public final class MongoConnectionHelper {

    private MongoConnectionHelper() {
    }

    public static MongoTemplate getMongoTemplate(ConnectString connectString) {
        MongoClient mongoClient = getMongoClient(connectString);
        String database = connectString.getSchema();
        SimpleMongoClientDatabaseFactory factory = new SimpleMongoClientDatabaseFactory(mongoClient, database);
        MongoTemplate mongoTemplate = new MongoTemplate(factory);
        return mongoTemplate;
    }

    public static MongoClient getMongoClient(ConnectString connectString) {
        String url = ConnectString.constructUrl(connectString);
        MongoClient mongoClient = MongoClients.create(url);
        return mongoClient;
    }

    public static boolean isValidConnection(ConnectString connectString) {
        try {
            MongoClient mongoClient = getMongoClient(connectString);
            String firstDb = mongoClient.listDatabaseNames().first();
            return firstDb != null && !firstDb.isEmpty();
        } catch (Exception e) {
            return false;
        }

    }

}
